import axios from "axios";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/store/user";

const service = axios.create({
  baseURL: import.meta.env.VITE_API_URL || "http://localhost:3000", // 替换为您的实际API地址
  timeout: 50000,
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const userStore = useUserStore();
    if (userStore.token) {
      config.headers["Authorization"] = `Bearer ${userStore.token}`;
    }
    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    if (![200, 201].includes(response.status)) {
      ElMessage({
        message: response.data?.message || "错误",
        type: "error",
        duration: 5 * 1000,
      });
      return Promise.reject(new Error(response.data?.message || "错误"));
    } else {
      return response;
    }
  },
  (error) => {
    const err = error.response?.data?.message || "错误";
    if ([401, 403].includes(error?.status)) {
      const userStore = useUserStore();
      userStore.logout();
    }
    ElMessage({
      message: err,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(err);
  }
);

export default service;
